import { defineStore } from 'pinia'
import { UserInfo, UserLoginPlayLoad } from '#/store'
import { Login, getUserInfo } from '@/api/user'

import { setCookies, removeCookies } from '@/utils/storage'
import { TokenKey } from '#/constant'
import { ResponseFormat } from '#/http'

interface UserState {
  userInfo: UserInfo | null
  token?: string;
  roles: [],
  routes: [],
  hasUserInfo: boolean,
  [key: string]: any;
}

// @ts-ignore
export const userStore = defineStore({
  id: 'app-user',
  state: (): UserState => ({
    userInfo: null,
    // token
    token: undefined,
    // 用户角色表
    roles: [],
    // 用户路由表
    routes: [],
    hasUserInfo: false
  }),
  getters: {
    getToken: (state) => {
      return state.token
    }
  },
  actions: {
    login (data: UserLoginPlayLoad): Promise<string | object> {
      return new Promise(async (resolve, reject) => {
        try {
          const res = await Login(data)
          if (res.data.Authorization) {
            this.token = res.data.Authorization
            setCookies(TokenKey, this.token)
            resolve('success')
          } else {
            reject('failure')
          }
        } catch (e: any) {
          reject(e)
        }
      })
    },
    queryUserInfo (): Promise<ResponseFormat> {
      return new Promise(async (resolve, reject) => {
        const res = await getUserInfo()
        this.userInfo = res.data
        this.hasUserInfo = true
      })
    },
    logout (): Promise<string | object> {
      return new Promise((resolve, reject) => {
        try {
          this.token = undefined
          // this.hasUserInfo = false
          removeCookies(TokenKey)
          resolve('logout successfully')
        } catch (e) {
          reject(e)
        }
      })
    }
  }
})
